<template>
  <view class="root">
    <view class="input-container bgc-fff mt-30">
      <textarea
        v-model="content"
        placeholder-class="color-8f9aa8 fs-26"
        maxlength="200"
        class="content"
        placeholder="输入您要发布的内容..."
      />
      <text class="color-bac4d0 fs-22 text-right"
        >{{ content.length }}/200</text
      >
    </view>
    <view class="main bgc-fff mt-30">
      <view class="tabs fd-row color-8f9aa8 fs-28">
        <text
          v-for="(item, index) in tabs"
          :key="index"
          @click="switchTab(index)"
          :class="['tab', { active: index == tabIndex }, 'pb-30', 'mr-50']"
          >{{ item }}</text
        >
      </view>
      <view class="operation-file mt-24">
        <view v-if="tabIndex == 0" class="image">
          <view class="show-picture fd-row">
            <view
              v-for="(item, index) in pictures"
              :key="index"
              class="picture"
            >
              <image
                class="icon-delete width-40 height-40 absolute right-0 top-0"
                src="/static/imgs/icon-delete.png"
                @click="operationImage('delete', index)"
              />
              <image
                class="width-100percent height-100percent absolute top-0 left-0"
                :src="item"
                mode="aspectFill"
                @click="operationImage('preview', index)"
              />
            </view>
            <view
              @click="operationImage('choose')"
              v-if="pictures.length < maxUploadImage"
              class="picture last"
            >
              <image
                class="absolute width-40 height-36"
                src="/static/imgs/icon-camera.png"
              />
            </view>
          </view>
          <text class="fs-24 color-8f9aa8 mt-30 text-right"
            >{{ pictures.length }}/6</text
          >
        </view>
        <view class="video ai-center" v-if="tabIndex == 1">
          <video v-if="video" :src="video" />
          <view
            v-else
            @click="chooseVideo"
            class="default-video width-100percent ai-center jc-center"
          >
            <image class="icon-video" src="/static/imgs/icon-video.png" />
          </view>
        </view>
      </view>
    </view>

    <button
      :style="{
        margin: `30px`,
        backgroundImage: `linear-gradient(90deg, #8ec5fc, #4388e7)`,
      }"
      hover-class="btn-hover"
      class="color-fff"
      @click="publish"
    >
      发布
    </button>
  </view>
</template>

<script>
  export default {
    data: () => ({
      content: "",
      tabs: ["图片", "视频"],
      userInfo: uni.getStorageSync("userInfo"),
      tabIndex: -1,
      video: "",
      maxUploadImage: 6,
      pictures: [],
    }),

    onLoad({ bid }) {
      this.bid = bid;
    },

    methods: {
      publish() {
        uni.showLoading({ title: "Loading...", mask: true });
        if (!this.content && !this.pictures.length && !this.video) {
          uni.hideLoading();
          uni.showToast({ title: "你还没有输入内容", icon: "none" });
          return;
        }
        if (!this.pictures.length && !this.video) {
          this.submit();
          return;
        }
        if (this.tabIndex) {
          uni.uploadFile({
            url: uni.REQUEST_URL + "/api/file/media",
            filePath: this.video,
            maxDuration: 15,
            name: "file",
            formData: { token: this.userInfo.token },
            fail: (res) => {
              console.log(res);
              uni.hideLoading();
              uni.showToast({
                title: "视频上传失败，请重试",
                icon: "none",
              });
            },
            success: ({ data }) =>
              this.submit(this.tabIndex, JSON.parse(data).data.path),
          });
        } else {
          let uploaded = [];
          this.pictures.some((filePath, sn) => {
            uni.uploadFile({
              url: uni.REQUEST_URL + "/api/file/media",
              filePath,
              name: "file",
              formData: { token: this.userInfo.token },
              fail: (res) => {
                console.log(res);
                uni.hideLoading();
                uni.showToast({
                  title: "图片上传失败，请重试",
                  icon: "none",
                });
                return true;
              },
              success: ({ data }) => {
                let resData = JSON.parse(data);
                if (resData.code == 200) {
                  uploaded.push({ sn, path: resData.data.path });
                  uploaded.length == this.pictures.length &&
                    this.submit(
                      this.tabIndex,
                      uploaded
                        .sort((a, b) => a.sn - b.sn)
                        .map((item) => item.path)
                        .join(",")
                    );
                } else {
                  uni.showToast({
                    title: `图(${uploaded.length}): ${resData.msg}, 请重试！`,
                  });
                  return true;
                }
              },
            });
          });
        }
      },
      submit(type, files) {
        uni.fetch("/api/bbs/note", {
          data: { bid: this.bid, text: this.content, type, files },
          success: (res) =>
            uni.showToast({
              title: "发布成功！",
              duration: 1200,
              success: () => {
                uni.$emit("refresh", { msg: "刷新数据" });
                setTimeout(uni.navigateBack, 1200);
              },
            }),
        });
      },
      switchTab(index) {
        this.tabIndex = index;
      },
      operationImage(mode, current) {
        switch (mode) {
          case "delete":
            this.pictures.splice(current, 1);
            break;
          case "preview":
            uni.previewImage({
              current,
              urls: this.pictures,
              indicator: "number",
            });
            break;
          default:
            uni.chooseImage({
              count: this.maxUploadImage - this.pictures.length,
              success: (res) => this.pictures.push(...res.tempFilePaths),
            });
            break;
        }
      },
      chooseVideo() {
        uni.chooseVideo({
          count: 1,
          maxDuration: 15,
          success: (res) => (this.video = res.tempFilePath),
        });
      },
    },
  };
</script>

<style>
  .input-container {
    padding: 30rpx;
  }
  .content {
    width: 100%;
    height: 200rpx;
  }
  .main {
    padding: 30rpx;
  }
  .tabs {
    border-bottom: 1rpx solid #ebebeb;
  }
  .tab.active {
    border-bottom: 3rpx solid #4371ff;
    color: #333;
  }
  .show-picture {
    flex-wrap: wrap;
  }
  .picture {
    overflow: hidden;
    position: relative;
    width: calc((100% - 72rpx) / 3);
    padding-bottom: calc((100% - 72rpx) / 3);
    margin: 12rpx;
    border-radius: 5rpx;
    height: 0;
  }
  .icon-delete {
    z-index: 9;
  }
  .picture.last {
    background-color: #f7f7f7;
    border: 1rpx solid #e6e6e6;
    border-radius: 5rpx;
    align-items: center;
  }
  .picture.last image {
    top: 50%;
    transform: translateY(-50%);
  }
  .default-video {
    background-color: #f7f7f7;
    border: 1rpx solid #e6e6e6;
    height: 320rpx;
  }
  .icon-video {
    width: 120rpx;
    height: 100rpx;
  }
</style>